package com.tledu.stu_manager.controller.login; /**
 *
 */

import com.alibaba.fastjson.JSONObject;
import com.tledu.stu_manager.constant.Constant;
import com.tledu.stu_manager.constant.SessionConstant;
import com.tledu.stu_manager.dao.StudentDao;
import com.tledu.stu_manager.exception.CustomException;
import com.tledu.stu_manager.model.Student;
import com.tledu.stu_manager.result.Result;
import com.tledu.stu_manager.service.LoginService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "LoginServlet", urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    private LoginService loginService;

    @Override
    public void init() throws ServletException {
        super.init();
        loginService = new LoginService(new StudentDao());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType(Constant.CONTENT_TYPE);
        PrintWriter out = response.getWriter();

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        try {
            Student student = loginService.login(username, password);
            HttpSession session = request.getSession();
            session.setAttribute(SessionConstant.CURRENT_LOGIN_USER, student);
            out.print(JSONObject.toJSONString(new Result<Student>(200, true, "登录成功", student)));
        } catch (CustomException e) {
            e.printStackTrace();
            out.print(JSONObject.toJSONString(new Result(500, false, e.getMessage())));
        }


    }
}
